﻿'use strict';
// 加载模块
//var $stateProviderRef = null; //初始化路由对象（替代作用） 'ui.router', "oc.lazyLoad", 'Common'
var jisuStuApp = angular.module('jisuStuHome', ['monospaced.qrcode','ngAnimate', 'ui.tree', 'ui.router', 'oc.lazyLoad','Common','loadModule','StuRequestTrain','angularFileUpload', 'vModal',   'dropdownApp', 'tm.pagination','filepreview','PensonSelector', 'personnelmanagementS', 'knowledgebaseS', 'interlocutionService', 'nstdirective','wangeditordrective','pascalprecht.translate','720kb.tooltips','HeadImgCrop','trainingTaskPreview','personnelLabel']); //我们把每个界面封装成一个模块 msgReader
//国际化（配置） 
jisuStuApp.config(['$translateProvider', function ($translateProvider) {
    var lang = window.localStorage.lang;
    if(lang==null||lang==undefined||lang==""){
        lang='cn';
        window.localStorage.lang=lang;
    }
    $translateProvider.preferredLanguage(lang);
    $translateProvider.useStaticFilesLoader({
        prefix: '/framework/i18n/',
        suffix: '.json'
    });
 }]);
//国际化（模板过滤器，模板使用）
jisuStuApp.filter("T", ['$translate', function($translate) {
    return function(key) {
        if(key){
            return $translate.instant(key);
        }
    };
}]);
//国际化（声明服务，控制器使用）
jisuStuApp.factory('T', ['$translate', function($translate) {
    var T = {
        T:function(key) {
            if(key){              
                return $translate.instant(key);
            }
            return key;
        }
    }
    return T;
}]);
jisuStuApp.controller('customerController', ['$scope','$rootScope', 'StuRequestTrain', 'sysUserInfo', 'Msg', function ($scope, $rootScope, ST, sysUserInfo, Msg) {

     //初始化  客服
    $scope.initkf = function () {
        $scope.params = {
            orgId: sysUserInfo.getuserinfo().organization_ID,
            orgName: sysUserInfo.getuserinfo().organization_Name
        };

        $scope.getcusList();
    }
    //查询
    // 企业的客服列表
    $scope.getcusList = function () {
        ST.findCustomer($scope.params).then(function (response) {
            if (response.errorcode == "0") {// 成功       
                $scope.cusList = response.datas;
                console.log("有客服数据");
                console.log($scope.cusList);
            } else {   // 获取失败 
                Msg.error("获取失败！");
            }
        }, function errorCallback() {
            console.log("连接服务器失败！");
        });
    }
   //$scope.initkf();

}]);

//'cgBusy','FileSelect', 
//实现无限嵌套的路由器器地址,每个界面都可以定义controller
/**
 * 由于整个应用都会和路由打交道，所以这里把$state和$stateParams这两个对象放到$rootScope上，方便其它地方引用和注入。
 * 这里的run方法只会在angular启动的时候运行一次。
 * @param  {[type]} $rootScope
 * @param  {[type]} $state
 * @param  {[type]} $stateParams
 * @return {[type]}
 */
jisuStuApp.run(function ($rootScope, $state, $stateParams, $animate, Restangular, sysUserInfo,Msg) {    
    $rootScope.$state = $state;
    
    var token="";
    if(window.location.hash.indexOf("token")!=-1){
        token=window.location.hash.split("token=")[1];
        sysUserInfo.setuserinfotoken(token);
    }

      //全局监听  当模板开始解析之前触发
    $rootScope.$on('$stateChangeStart',function(event, viewConfig){             
        $rootScope.allLoadingShow = true;  
     });
     // 当模板解析完成后触发
    $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){                          
        $rootScope.allLoadingShow = false;
    });

    $rootScope.$stateParams = $stateParams;
    $animate.enabled(true); //启动动画    
    Restangular.addFullRequestInterceptor(function(element, operation, route, url, headers, params, httpConfig) {
        //这个地方需要把登录得到的token写入到请求数据的头文件中
//        console.log('请求时自动写入token ' + url);
        //console.log(sysUserInfo.getuserinfotoken());
//
            var usertoken  = sysUserInfo.getuserinfotoken().toString();
            if(usertoken == undefined || usertoken == null || usertoken == ""){
                localStorage.clear();
                location.href="/login.html";
            }
            return {              
                headers: {"X-Session-Token": usertoken}  
            };
    });
    Restangular.addResponseInterceptor(function (data, operation, what, url, response, deferred) {
        if(data.errorcode=="35"){
            sysUserInfo.clearuserinfo();
            Msg.error("严重","用户token鉴权失败,请重新登录!");        
            data.errorcode =0;      
        }
        if(data.errorcode == "36"){
            sysUserInfo.clearuserinfo();
            Msg.error("严重","用户鉴权过期请重新登录！");  
            data.errorcode =0;      
        }
        return data;
    });
    Restangular.setErrorInterceptor(function (response, deferred, responseHandler) {
        $rootScope.errinfo = "<font color=\"red\">服务器宕机或网络不可用！</font><a href=\"/login.html\">重新登录</a>";
        if (response.status === 200) {
            return true;
        } else {
            console.log('获取数据异常了！ ' + response.status);
        }
    });
    $rootScope.loadshow = true;
    $rootScope.stuMenuList= [];
    $rootScope.stuMenuLang=window.localStorage.lang =='cn'?true:false;
    var errorinfoplay = localStorage.getItem("errorinfo");
    if (errorinfoplay == null || errorinfoplay == undefined || errorinfoplay == "") {     // 从二级运营中跳转过的运营管理企业的判断
        $rootScope.errinfo = "正在拼命加载中...";
    } else {
        $rootScope.errinfo = "正在为您跳转到" + errorinfoplay + "企业当中...请稍后！";
        localStorage.setItem("errorinfo", "");
    }
   var userinfo=localStorage.getItem("userinfo");
   if(userinfo!=undefined&&userinfo!=null&&userinfo.length>0){
        userinfo=JSON.parse(userinfo);
    }
    // 判断用户是否已经登录返回登录页
    var a=window.location.hash;
    //题库跳转
    if(a.indexOf("/0/phone")!=-1){
        var preurl=a.split("/0/phone")[0];
        //用户id
        var b=preurl.substr(preurl.lastIndexOf("/")+1,preurl.length);
//        if(token==undefined||token==null||token.length<=0){
//            window.location.href = "/login.html";
//        }
        if (userinfo==undefined|| userinfo== null || userinfo.user_ID == undefined||b!=userinfo.user_ID) {
                localStorage.setItem("quesUrl",window.location.href);
                window.location.href = "/user/ques_login.html#"+b+"/"+token;
        }
    }
     if (userinfo!=undefined&&userinfo!= null &&userinfo.user_ID!=undefined) {
        $rootScope.systemTitle = sysUserInfo.getuserinfo().organization_Name;
         Restangular.one("/organizationInfo").customPOST({ name: "My Message" }, "findOrgInfo", { orgId: sysUserInfo.getuserinfo().organization_ID}).then(function(response){
            if(response.errorcode ==0){
                var orginfo = response.data;
                if(orginfo.orgContent){
                    $rootScope.stuMenuList = JSON.parse(orginfo.orgContent);                    
                }else{
                    $rootScope.stuMenuList = sysUserInfo.getStuMenuList();    
                }
                sysUserInfo.setorganizationinfo(orginfo);
                $rootScope.loadshow = false;    
                //console.log($rootScope.stuMenuList,window.localStorage.lang);                                    
            }else{
              $rootScope.errinfo = "<font color=\"red\">用户信息获取失败！</font><a href=\"/\">重新登录</a>";
            }
         });
    }
//        Restangular.one("/PersonnelManagement").customPOST({ name: "My Message" }, "PersonnelGetKey", { user_ID: sysUserInfo.getuserinfo().user_ID }).then(function (retobj) {
//            if (retobj.errorcode == 0) {
//                //用户信息查询保存
//                retobj.data.user_ID;
//                retobj.data.user_Name;
//                if (retobj.data.user_Img == "" || retobj.data.user_Img == null || retobj.data.user_Img == undefined) {
//                    retobj.data.user_Img = "/images/avatar.png";
//                }
//                retobj.data.userId=retobj.data.user_ID;
//                sysUserInfo.setuserinfo(retobj.data);
//                $rootScope.loadshow = false;
//            } else {
//                $rootScope.errinfo = "<font color=\"red\">服务器访问异常！</font><a href=\"/login.html\">重新登录</a>";
//            }
//        }, function errorCallback() {
//            $rootScope.errinfo = "<font color=\"red\">服务器宕机或网络不可用！</font><a href=\"/login.html\">重新登录</a>";
//        });

});
jisuStuApp.constant('Modules_Config', [{    //当有需要的时候加在预定义模块
    name: 'gridModule',
    serie: true,
    files: [{
        type: 'css',
        path: 'http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css'
    }]
}]);

/**
 * 配置路由。
 * 注意这里采用的是ui-router这个路由，而不是ng原生的路由。
 * ng原生的路由不能支持嵌套视图，所以这里必须使用ui-router。
 * main@index的意思是main是view标签的名字
 * @param  {[type]} $stateProvider
 * @param  {[type]} $urlRouterProvider
 * @return {[type]} toastrConfig 配置消息弹出样式
 * @return {[type]} RestangularProvider 数据请求
 */
jisuStuApp.config(['$stateProvider', '$urlRouterProvider', '$oclazyloadProvider', 'toastrConfig',  'Modules_Config',
function($stateProvider, $urlRouterProvider, $oclazyloadProvider, toastrConfig,  Modules_Config) {
    //全局设置AJAX数据请求地址       
    //RestangularProvider.setRequestSuffix('.json'); //这个后缀名在正式项目中删除掉    
    //$stateProviderRef = $stateProvider; //将定义路由的对象赋值给定义好的变量方便抛出使用原因是config 中不能用区域变量
    //配置异步加载器
    $oclazyloadProvider.config({
        debug: false,
        events: false,
        modules: Modules_Config
    });

    //配置路由器
    $urlRouterProvider.otherwise('/home');
    $stateProvider.state('home', {
        url: '/home',
        data: {},
        views: {
            '': {
                templateUrl: 'view/home.html'
            },
            'topbar@home': {
                templateUrl: 'view/topbar.html',                
            },
            'main@home': {
                templateUrl: 'view/index.html'
            }
        },
        resolve: {
             modules: ['$oclazyload',
                function($oclazyload) {
                    return $oclazyload.load([{
                        serie: true,
                        files: ["/member/controller/home.js","/member/directive/jisustuapp.js","/member/controller/stutrainlist.js"]
                    }]);
            }]           
        }
    })
    // 培训
    .state('home.train', {
        url: '/train',
        views: {
            'main@home': {
                templateUrl: 'view/trainhome.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                            files:["/system/service/trainpathservice.js","/member/directive/jisustuapp.js","/member/controller/home.js"]                           
                        });
                    }]
                }
            
    })

    // 公开课
    .state('home.train.publiclist', {
        url: '/publiclist',
        views: {
            'main@home.train': {
                templateUrl: 'view/stupublicclass.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                            files:["/system/service/trainpathservice.js","/member/directive/jisustuapp.js","/member/controller/stupublicclass.js"]                           
                        });
                    }]
                }
            
    })
    // 培训
    .state('home.train.task', {
        url: '/task',
        views: {
            'main@home.train': {
                templateUrl: 'view/stutrainlist.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                            files:["/system/service/trainpathservice.js","/member/directive/jisustuapp.js","/member/controller/stutrainlist.js"]                           
                        });
                    }]
                }
            
    })
    //任务详情
    .state('home.train.publictask', {
        url: '/publictask',
        views: {
            'main@home.train': {
                templateUrl: 'view/publictask.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                            files:["/member/controller/publictask.js"]                           
                        });
                    }]
                },
        params: {renwuobj:null}
    })



     // 班级
    .state('home.train.questionnaire', {
        url: '/questionnaire',
        views: {
            'main@home.train': {
                templateUrl: '/member/view/questionnaire.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                            files:["/member/controller/questionnaire.js"]                           
                        });
                    }]
                }
            
    })

 
    // 知识库
    .state('home.knowledge', {
        url: '/knowledge',
        views: {
            'main@home': {
                templateUrl: 'view/knowledge.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                            files:["/system/service/trainpathservice.js","/system/service/personnelpathservice.js","/member/controller/knowledge.js","/system/directive/train/movefile.js","/system/directive/train/fileshare.js"]                           
                        });
                    }]
                }
            
    })  
    /************************************************问答***************************************************/
    //栏目列表
    .state('home.interlocution', {
        url: '/interlocution',
        views: {
            'main@home': {
                templateUrl: 'view/interlocution/home.html'},
            'main@home.interlocution': {
                templateUrl: 'view/interlocution/interlocution.html'}
                },
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                           files:["/system/service/trainpathservice.js","/system/service/interlocutionservice.js","/member/controller/interlocution/stuinterlocution.js","/member/directive/interlocution/add_interlocution.js",
                           "/member/controller/interlocution/questionlist.js","/member/controller/interlocution/myfollowexpert.js","/member/controller/interlocution/myfollowcolnum.js",
                           "/member/controller/interlocution/myreplay.js","/member/controller/interlocution/expertdynamic.js","/member/controller/interlocution/collectionquestion.js",
                           "/member/controller/interlocution/myquestion.js","/member/controller/interlocution/questiondetail.js"]                                
                        });
                    }]
                }
            
    })  
     //我关注的专栏
    .state('home.interlocution.myfollowcolnum', {
        url: '/myfollowcolnum',
        views: {
            'main@home.interlocution': {
                templateUrl: 'view/interlocution/myfollowcolnum.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                           files:["/member/controller/interlocution/myfollowcolnum.js"]                        
                        });
                    }]
                }
            
    })  
     //我关注的专家
    .state('home.interlocution.myfollowexpert', {
        url: '/myfollowexpert',
        views: {
            'main@home.interlocution': {
                templateUrl: 'view/interlocution/myfollowexpert.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                           files:["/member/controller/interlocution/myfollowexpert.js"]                        
                        });
                    }]
                }
            
    })  
     //我的提问
    .state('home.interlocution.myQuestion', {
        url: '/myQuestion',
        views: {
            'main@home.interlocution': {
                templateUrl: 'view/interlocution/myquestion.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                           files:["/member/controller/interlocution/myquestion.js"]                        
                        });
                    }]
                }
            
    })  
     //我的回复
    .state('home.interlocution.myReplay', {
        url: '/myReplay',
        views: {
            'main@home.interlocution': {
                templateUrl: 'view/interlocution/myreplay.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                           files:["/member/controller/interlocution/myreplay.js"]                        
                        });
                    }]
                }
            
    })  
     //我关注的专家
    .state('home.interlocution.expertdynamic', {
        url: '/expertdynamic',
        views: {
            'main@home.interlocution': {
                templateUrl: 'view/interlocution/expertdynamic.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                           files:["/member/controller/interlocution/expertdynamic.js"]                        
                        });
                    }]
                }
            
    })
     //我收藏的问答
    .state('home.interlocution.collectionquestion', {
        url: '/collectionQuestion',
        views: {
            'main@home.interlocution': {
                templateUrl: 'view/interlocution/collectionquestion.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                           files:["/member/controller/interlocution/collectionquestion.js"]                        
                        });
                    }]
                }
            
    })  
    //问答列表
    .state('home.interlocution.questionlist', {
        url: '/questionlist',
        views: {
            'main@home.interlocution': {
                templateUrl: 'view/interlocution/questionlist.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                           files:["/member/controller/interlocution/questionlist.js"]                        
                        });
                    }]
                }
            
    })  
    //问答详细
    .state('home.interlocution.questiondetail', {
        url: '/questiondetail',
        views: {
            'main@home.interlocution': {
                templateUrl: 'view/interlocution/questiondetail.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                           files:["/member/controller/interlocution/questiondetail.js"]                        
                        });
                    }]
                }
            
    })  
   
 
    /*******************************************************************************************************/
    // 个人基本信息
    .state('home.stuinfo', {
        url: '/stuinfo',
        views: {
            'main@home': {
                templateUrl: 'view/stuhome.html'}, 
          'main@home.stuinfo': {
                templateUrl: 'view/stucoursecollection.html'}
                },
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                            files:["/system/service/trainpathservice.js","/system/service/personnelpathservice.js","/member/controller/stuinfo.js","/member/controller/stucoursecollection.js"]                           
                        });
                    }]
                }
            
    })
     // 课程收藏
    .state('home.stuinfo.coursecollection', {
        url: '/coursecollection',
        views: {
            'main@home.stuinfo': {
                templateUrl: 'view/stucoursecollection.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                            files:["/system/service/trainpathservice.js","/system/service/personnelpathservice.js","/member/controller/stucoursecollection.js"]                           
                        });
                    }]
                }
            
    })
    // 个人考试历史
    .state('home.stuinfo.examhistory', {
        url: '/examhistory',
        views: {
            'main@home.stuinfo': {
                templateUrl: 'view/stuexamhistory.html?v=0.1'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                    cache: false,
                            files:["/system/service/trainpathservice.js","/system/service/personnelpathservice.js","/member/controller/stuexamhistory.js"]                           
                        });
                    }]
                }
            
    })
     // 个人信息
    .state('home.stuinfo.gerenxinxi', {
        url: '/gerenxinxi',
        views: {
            'main@home.stuinfo': {
                templateUrl: 'view/stuinfo.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                            cache: false,
                            files:["/system/service/trainpathservice.js","/system/service/personnelpathservice.js","/member/controller/stuexamhistory.js","/system/directive/personnel/img-crop/head_img_crop.js","/system/service/statisticservice.js"] 
                        });
                    }]
                }
            
    })

    // 个人信息
    .state('home.stuinfo.ImageAcquisition', {
        url: '/ImageAcquisition',
        views: {
            'main@home.stuinfo': {
                templateUrl: 'view/imageacquisition.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                            cache: false,
                            files:["/member/controller/getUserMedia.js"] 
                        });
                    }]
                }
    })
     // 个人积分详情
    .state('home.stuinfo.integral', {
        url: '/integral',
        views: {
            'main@home.stuinfo': {
                templateUrl: 'view/integral.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                            cache: false,
                            files:["/system/service/interlocutionservice.js","/member/controller/integrallist.js"] 
                        });
                    }]
                }
            
    })
     // 题库练习列表
    .state('home.stuquelist', {
        url: '/stuquelist/:xid/:knowledgeId/:passtype/:pass/:typeId/:knowledgeName/:arrangeId/:parentId/:parentName/:parentCount/:userId/:totleTime/:backUrl',        
        //params:{ taskId: ""},
        
        //params:{ xid: "", knowledgeId:"",passtype:"",pass:"",typeId:"",knowledgeName:"",arrangeId:""},
        views: {
            'main@home': {
                templateUrl: 'view/stuquelist.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                            cache: false,
                            files:["/system/service/trainpathservice.js","/system/service/personnelpathservice.js","/member/controller/stuquelist.js"]                           
                        });
                    }]
                }
            
    })
    // 题库练习
    .state('home.stuqueinfo', {
        url: '/stuqueinfo',
        params:{ userQuestionsInfo: "", groupIndex:"", groupPath: "" },
        views: {
            'main@home': {
                templateUrl: 'view/stuqueinfo.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                            cache: false,
                            files:["/system/service/trainpathservice.js","/system/service/personnelpathservice.js","/member/controller/stuqueinfo.js"]                           
                        });
                    }]
                }
            
    })
    // 错题、收藏。知识架构
    .state('home.knowledgestructurelist', {
        url: '/knowledgestructurelist',
        params:{ knowledgeId: "",typeId:""},
        views: {
            'main@home': {
                templateUrl: 'view/knowledgestructurelist.html'}},
                resolve: {
                    modules: ['$oclazyload',
                    function($oclazyload) {
                        return $oclazyload.load({
                            serie: true,
                            cache: false,
                            files:["/system/service/trainpathservice.js","/system/service/personnelpathservice.js","/member/controller/knowledgestructurelist.js"]                           
                        });
                    }]
                }
            
    })

}]);
